/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler;

import java.util.Collection;

import org.apache.log4j.Logger;

import jp.aist.gtrc.plus.scheduler.job.JobStateType;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSScheduleStarter;
import jp.aist.gtrc.plus.scheduler.specific.sge.sched.SGEScheduleStarter;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.status.MainServer;
import jp.aist.gtrc.plus.scheduler.status.NodeStatus;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.util.LogUtil;


public class SimpleFifoScheduler {

        protected static final Logger logger = Logger.getLogger(SimpleFifoScheduler.class);

	public static ScheduleStarter makeStarter(String[] args) throws Exception {

		String type = (args.length == 0) ? "sge" : args[0];

		if (type.equalsIgnoreCase("pbs"))
			return new PBSScheduleStarter();
		else if (type.equalsIgnoreCase("sge"))
			return new SGEScheduleStarter();
		else
			throw new Exception("\"pbs\" or \"sge\" only supported");

	}

	public static void main(String[] args) {

		try {
			LogUtil.initWithCmdLog();

			ScheduleStarter starter = makeStarter(args);
			ScheduleOrder order = null;
			do {
				order = starter.waitOrder();
				MainServer srv = order.getMainServer();
				try {
					schedule(srv);
				} catch (SchedulerException e) {
					// ignore to continue scheduling
					e.printStackTrace();
				} finally {
					srv.disconnect();
				}
			} while (order.toBeQuit() == false);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void schedule(MainServer srv) throws SchedulerException {

                logger.debug("SimpleFifoScheduler does scheduling");
		Collection<NodeStatus> nodes = srv.getNodeStatus();
		for (JobStatus job : srv.getJobStatus()) {
			if (job.getState() == JobStateType.Queued) {
				for (NodeStatus node : nodes) {
					// run this job on a first found node
					srv.runJob(job.getJobID(), node);
					return;
				}
			}
		}

	}

}
